﻿using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ldhWebApiIIS.middleware
{
    public class CheckIPMiddleware
    {
        public static List<string> IpWhitelist { get; internal set; }
        private readonly RequestDelegate _next;

        public CheckIPMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            //enable corss domain ajax access
            if (context.Request.Method == "OPTIONS")
            {
                await _next.Invoke(context);
                return;
            }

            if (IpWhitelist.FirstOrDefault() == "0.0.0.0/0")
            {
                await _next.Invoke(context);
                return;
            }

            var removeip = context.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.MapToIPv4().ToString();
            if (IpWhitelist.Contains(removeip))
            {
                await _next.Invoke(context);
                return;
            }
            
            await Task.Run(() => { context.Response.StatusCode = 429; }); 
        }
    }
}
